<?php
/*
|--------------------------------------------------------------------------
| Common function method
|--------------------------------------------------------------------------
*/

use Hyperf\Contract\StdoutLoggerInterface;
use Hyperf\Guzzle\ClientFactory;
use Hyperf\HttpServer\Contract\ResponseInterface;
use Hyperf\Logger\LoggerFactory;
use Hyperf\Server\ServerFactory;
use Hyperf\Context\ApplicationContext;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ServerRequestInterface;

/**
 * 输出多个参数
 */
if (!function_exists('dd')) {
    function dd(...$vars)
    {
        if (!in_array(\PHP_SAPI, ['cli', 'phpdbg'], true) && !headers_sent()) {
            header('HTTP/1.1 500 Internal Server Error');
        }
        foreach ($vars as $v) {
            var_dump($v);
        }
        exit(1);
    }
}

if (!function_exists('container')) {
    /**
     * 容器实例
     * @return ContainerInterface
     */
    function container()
    {
        return ApplicationContext::getContainer();
    }
}

if (!function_exists('config')) {
    function config()
    {
        return container()->get(\Hyperf\Config\Config::class);
    }
}

if (!function_exists('redis')) {
    /**
     * Redis 客户端实例
     * @param string $name
     * @return mixed
     * @throws mixed
     */
    function redis($name = 'default')
    {
        return container()->get(\Hyperf\Redis\RedisFactory::class)->get($name);
    }
}

if (!function_exists('guzzle_http')) {

    /**
     * 创建 guzzle-http 客户端
     * @return mixed
     * @throws mixed
     */
    function guzzle_http(): GuzzleHttp\Client
    {
        return container()->get(ClientFactory::class)->create();
    }
}

if (!function_exists('server')) {
    /**
     * Server 实例 基于 Swoole Server
     * @return mixed
     * @throws mixed
     */
    function server()
    {
        return container()->get(ServerFactory::class)->getServer()->getServer();
    }
}

if (!function_exists('cache')) {
    /**
     * 缓存实例 简单的缓存
     * @return mixed
     * @throws mixed
     */
    function cache()
    {
        return container()->get(Psr\SimpleCache\CacheInterface::class);
    }
}

if (!function_exists('stdout_log')) {
    /**
     * 控制台日志实例
     * @return mixed
     * @throws mixed
     */
    function stdout_log()
    {
        return container()->get(StdoutLoggerInterface::class);
    }
}

if (!function_exists('logger')) {
    /**
     * 文件日志实例
     * @param string $name
     * @param string $group default,或者shell
     * @return mixed
     * @throws mixed
     */
    function logger(string $name = 'app', string $group = 'shell')
    {
        return container()->get(LoggerFactory::class)->get($name, $group);
    }
}

if (!function_exists('request')) {
    /**
     * Http 请求实例
     * @return mixed
     * @throws mixed
     */
    function request()
    {
        return container()->get(ServerRequestInterface::class);
    }
}

if (!function_exists('response')) {
    /**
     * Http 响应实例
     * @return mixed
     * @throws mixed
     */
    function response()
    {
        return container()->get(ResponseInterface::class);
    }
}

if (!function_exists('event')) {
    /**
     * Dispatch an event and call the listeners.
     */
    function event()
    {
        return container()->get(Psr\EventDispatcher\EventDispatcherInterface::class);
    }
}

/**
 * 获取客户端你真实IP
 * @return mixed|string
 */
function getRealIp(): string
{
    if ($ip = request()->getHeaderLine('x-real-ip')) {
        return $ip;
    } else if ($ip = request()->getHeaderLine('x-forwarded-for')) {
        return $ip;
    }
    return request()->getServerParams()['remote_addr'] ?? '';
}

/**
 * 取出一个价格里多余的0
 */
function filterZero(mixed $str)
{
    return intval(floatval($str) + 0);
}

/**
 * 获取xml名称
 */
if (!function_exists('getXmlName')) {
    function getXmlName(string $str)
    {
        if (!str_contains($str, '.xml')) {
            return '';
        }
        if (strpos($str, '.php/') !== false) {
            $str = explode(".php/", $str);
            $str = $str[count($str) - 1];
        } elseif (strpos($str, '.php?') !== false) {
            $str = explode(".php?", $str);
            $str = $str[count($str) - 1];
        } elseif (str_contains($str, '?')) {
            $str = substr($str, strrpos($str, '?') + 1);
        }
        return str_replace('.xml', '', basename($str));
    }
}

/**
 * 向远程提交跳转数据
 */
if (!function_exists('saveJumpData2Remote')) {
    function saveJumpData2Remote($url, $data = array())
    {
        $url = str_replace(' ', '+', $url);
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, "$url");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_TIMEOUT, 2);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        $output = curl_exec($ch);
        $errorCode = curl_errno($ch);
        curl_close($ch);
        if (0 !== $errorCode) {
            return false;
        }
        return $output;
    }
}

if (!function_exists('getMicrotime')) {
    function getMicrotime()
    {
        list($usec, $sec) = explode(" ", microtime());
        return ((float)$usec + (float)$sec);
    }
}

/**
 * 扩展请求参数
 */
if (!function_exists('getExtendParams')) {
    function getExtendParams(array $params)
    {
        $params['domain'] = trim($params['domain'], '/');
        $params['domain_nohttp'] = str_replace(['http://', 'https://'], '', $params['domain']);
        $params['domain_nowww'] = str_replace(['http://', 'https://', 'www.'], '', $params['domain']);
        $params['uri'] = urldecode(str_replace(' ', '', $params['uri']));
        $params['uri'] = htmlspecialchars_decode($params['uri']);
        $params['ip'] = $params['ip'] ?? '';

        if (!in_array($params['port'], [0, 80, 443]) && !str_contains($params['domain'], ':' . $params['port'])) {
            $params['url'] = $params['domain'] . ':' . $params['port'] . $params['uri'];
        } else {
            $params['url'] = $params['domain'] . $params['uri'];
        }
        $params['url_nohttp'] = str_replace(['http://', 'https://'], '', $params['url']);
        $params['url_nowww'] = str_replace('www.', '', $params['url_nohttp']);

        $parse = parse_url(str_replace('=&', '=', $params['url']));
        $params['separator'] = '/';
        if (isset($parse['query']) && !empty($parse['query'])) {
            $params['separator'] = '?';
            if (isset($parse['path']) && !empty($parse['path']) && str_ends_with($parse['path'], '/')) {
                $params['separator'] = '/?';
            }
        }
        if (!in_array($params['port'], [0, 80, 443]) && !str_contains($params['domain'], ':' . $params['port'])) {
            $params['host'] = $params['domain'] . ':' . $params['port'] . $params['separator'];
        } else {
            $params['host'] = $params['domain'] . $params['separator'];
        }
        $params['hosturl'] = $params['host'];
        $params['hosturl2'] = $params['domain']; // 不加分隔符的
        $pos = strpos(strtolower($params['uri']), '.php');
        if ($pos !== false) {
            preg_match('/\/([^\/]+\.php)/', $params['uri'], $matches);
            $phpFileName = $matches[1] ?? '';
            if (!in_array($phpFileName, ['', 'default.php'])) {
                if (!in_array($params['port'], [0, 80, 443]) && !str_contains($params['domain'], ':' . $params['port'])) {
                    $params['hosturl'] = $params['domain'] . ':' . $params['port'] . '/' . $phpFileName . $params['separator'];
                    $params['hosturl2'] = $params['domain'] . ':' . $params['port'] . '/' . $phpFileName;
                } else {
                    $params['hosturl'] = $params['domain'] . '/' . $phpFileName . $params['separator'];
                    $params['hosturl2'] = $params['domain'] . '/' . $phpFileName;
                }
            }
        }
        // $params['hosturl'] = rtrim($params['hosturl'], '/?') . '/';
        return $params;
    }
}

if (!function_exists('randomkeys')) {
    function randomkeys(int $length, int $flag = 0)
    {
        $key = '';
        if ($flag === 1) {
            $pattern = str_split('abcdefghijklmnopqrstuvwxyz');
        } else if ($flag === 2) {
            $pattern = str_split('1234567890');
        } else {
            $pattern = str_split('abcdefghijklmnopqrstuvwxyz1234567890');
        }
        $count = count($pattern) - 1;
        for ($i = 0; $i < $length; $i++) {
            $key .= $pattern[mt_rand(0, $count)];
        }
        return $key;
    }
}

/**
 * 获取商品ID
 */
if (!function_exists('getProductId')) {
    function getProductId(string $url, int $maxId, int $zhongzi)
    {
        $url = str_replace('/?', '/', rtrim($url, '/'));
        $init = $url;
        if (str_contains($url, '.php?')) {
            $arr = explode('.php?', $url);
            $arr = explode('/', $arr[count($arr) - 1]);
        } elseif (str_contains($url, '.php/')) {
            $arr = explode('.php/', $url);
            $arr = explode('/', $arr[count($arr) - 1]);
        } else {
            $arr = explode('/', $url);
        }
        $arr = array_filter($arr);
        $url = $arr[count($arr) - 1] ?? '';
        $pid = 0;
        if (!empty($url)) {
            $url = str_replace(array('.shtml', '.html', '.htm', '.phtm'), '', $url);
            preg_match("#\d+#", $url, $out);
            $loc = $out[0] ?? '';
            $len = mb_strlen($loc);
            $pid = $len === 9 ? intval(mb_substr($loc, -7)) : 0;
        }
        $mymax = $maxId + $zhongzi;
        if ($pid > $zhongzi && $pid <= $mymax) {
            return $pid - $zhongzi;
        } else {
            mt_srand(crc32($init));
            $pid = mt_rand(1, $maxId);
            mt_srand();
            return $pid;
        }
    }
}

/**
 * 根据商品ID获取商品文件中的内容
 */
if (!function_exists('getProductContent')) {
    function getProductContent(int $pid, int $dirnum)
    {
        $subDir = ceil($pid / $dirnum);
        $productPath = BASE_PATH . '/storage/products/' . $subDir . '/' . $pid . '.txt';
        $productContent = @file_get_contents($productPath);
        return !empty($productContent) ? explode("|||", $productContent) : [];
    }
}